﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Tilver.Web
{
    /// <summary>
    /// HTTP的GET请求类
    /// 用于GET到URL并获得返回结果
    /// </summary>
    public class WebGetRequest
    {
        /// <summary>
        /// 访问的URL
        /// </summary>
        public string Url { get; internal set; }

        /// <summary>
        /// 访问URL的字符集
        /// </summary>
        public Encoding Encoding { get; internal set; }

        /// <summary>
        /// 访问时包含的Cookie
        /// </summary>
        public CookieContainer Cookie { get; internal set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="url">访问的URL</param>
        /// <param name="encoding">访问URL的字符集</param>
        /// <param name="cookie">访问时包含的Cookie</param>
        public WebGetRequest(string url, Encoding encoding = null, CookieContainer cookie = null)
        {
            Url = url;
            Encoding = encoding ?? Encoding.UTF8;
            Cookie = cookie;
        }

        /// <summary>
        /// 获得URL返回结果
        /// </summary>
        /// <returns></returns>
        public string GetResponse()
        {
            using (Stream stream = GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(stream, Encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <summary>
        /// 获得URL返回结果
        /// </summary>
        /// <returns></returns>
        public Stream GetResponseStream()
        {
            HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest;
            request.Method = "GET";
            request.KeepAlive = false;
            request.CookieContainer = Cookie;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            return response.GetResponseStream();
        }
    }
}
